package com.doublefish.doublefishrobot.ui.home;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.doublefish.doublefishrobot.BuildConfig;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.ui.home.adapter.BindDeviceListAdapter;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.ui.home.widget.Banner;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.MessageEvent;
import com.doublefish.doublefishrobot.utils.ToastUtil;
import com.doublefish.doublefishrobot.utils.ble.DFBleManager;
import com.doublefish.doublefishrobot.utils.ble.DFS6ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.DFS8ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.bean.BleMachineInfoBean;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.ble.bean.OnBleResponseHandler;
import com.doublefish.doublefishrobot.utils.db.DataBaseApi;
import com.doublefish.doublefishrobot.utils.socket.SocketManager;
import com.doublefish.doublefishrobot.widget.CommonDialog;
import com.doublefish.doublefishrobot.widget.LoadingDialog;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者:dugaofeng on 2024/10/15 17:12
 */
public class HomeFragment extends Fragment implements DFBleManager.OnBleManagerListner{

    private View view;

    private View backLL;
    private TextView titleTv;
    private TextView rightTv;

    private Banner banner;

    private TextView countTv;
    private SwipeRecyclerView recyclerView;

    private BindDeviceListAdapter adapter;
    private List<DeviceBean> bindList = new ArrayList<>(); //已绑定设备列表

    private boolean didInitView = false;  //页面已经初始化

    private OnToModeMenuListner onToModeMenuListner;
    private OnCheckPermissonsListner onCheckPermissonsListner;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home, container, false);
            EventBus.getDefault().register(this);
            initViews();
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        DFBleManager.getInstance().setOnBleManagerListner(this);
        if (didInitView) {
            //从数据库查找已绑定设备列表
            queryBindList();
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (MessageEvent.BIND_DEVICES_CHANGED_NOTI.equals(event.getTag())) {
            if (didInitView) {
                //从数据库查找已绑定设备列表
                queryBindList();
            }
        }
    }

    private void initViews() {
        backLL = view.findViewById(R.id.ll_back);
        backLL.setVisibility(View.INVISIBLE);

        titleTv = view.findViewById(R.id.tv_title);
        titleTv.setText(R.string.tab_home);

        rightTv = view.findViewById(R.id.tv_right);
        rightTv.setOnClickListener(this::onRightBtnClick);
        rightTv.setBackground(getResources().getDrawable(R.mipmap.icon_add));
        if (BuildConfig.DEBUG) {
            //测试代码 荣耀手机的右边不响应
            titleTv.setOnClickListener(this::onRightBtnClick);
        }

        banner = view.findViewById(R.id.home_banner);
        countTv = view.findViewById(R.id.tv_count);
        recyclerView = view.findViewById(R.id.recyclerView);

        //banner数据
        List<Banner.HomeBannerBean> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Banner.HomeBannerBean bannerBean = new Banner.HomeBannerBean();
            bannerBean.setResId(R.mipmap.banner_0);
            list.add(bannerBean);
        }
        banner.setBannerBeanList(list);

        //侧滑删除
        createSwipeMenu();

        adapter = new BindDeviceListAdapter(getActivity(), bindList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                DeviceBean bindBean = bindList.get(position);
                bindListItemClick(bindBean);
            }
        });

        didInitView = true;
    }

    //创建侧滑菜单
    private void createSwipeMenu() {
        // 创建侧滑菜单
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
                //删除菜单
                SwipeMenuItem infoItem = new SwipeMenuItem(getActivity());
                infoItem.setBackgroundColor(getResources().getColor(R.color.red));
//                infoItem.setImage(R.mipmap.icon_info);
                infoItem.setText(getString(R.string.info));
                infoItem.setTextColor(getResources().getColor(R.color.white, null));
                infoItem.setWidth(dip2px(70));
                infoItem.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);

                rightMenu.addMenuItem(infoItem);
            }
        };
        recyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
        recyclerView.setItemViewSwipeEnabled(false); //侧滑删除

        //菜单点击监听
        recyclerView.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge swipeMenuBridge, int i) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                swipeMenuBridge.closeMenu();

                DeviceBean bindBean = bindList.get(i);
                toDeviceInfoActivity(bindBean);
            }
        });
    }

    public void setOnToModeMenuListner(OnToModeMenuListner onToModeMenuListner) {
        this.onToModeMenuListner = onToModeMenuListner;
    }

    public void setOnCheckPermissonsListner(OnCheckPermissonsListner onCheckPermissonsListner) {
        this.onCheckPermissonsListner = onCheckPermissonsListner;
    }

    public void onRightBtnClick(View view) {
        Intent intent = new Intent(getActivity(), DevicesBindActivity.class);
        startActivity(intent);
    }

    //从数据库查找已绑定设备列表
    private void queryBindList() {
        //debug
//        int n = 1;
//        if (1 == n) {
//            DeviceBean deviceBean = new DeviceBean();
//            deviceBean.setName("test");
//            deviceBean.setMac("12312321");
//            deviceBean.setAlias("007");
//            deviceBean.setMachineID(1234);
//            deviceBean.setDeviceType(ModeConstant.DeviceTypeS5);
//
//            DataBaseApi.saveDeviceInfo(deviceBean, new DataBaseApi.OnDatabaseCommonListner() {
//                @Override
//                public void onCallback(boolean suc) {
//                    Log.i("xxxx", "xxxx");
//                }
//            });
//            return;
//        }

        DataBaseApi.queryBindDeviceList(new DataBaseApi.OnQueryBindDeviceListListner() {
            @Override
            public void onCallback(boolean suc, List list) {
                if (suc) {
                    bindList.clear();
                    if (list == null) {
                        countTv.setText(getString(R.string.total_bind) +  "·0");
                    } else {
                        bindList.addAll(list);
                        countTv.setText(getString(R.string.total_bind) + "·" + bindList.size());
                    }
                    AppCacheUtil.getInstance().setBindList(bindList);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    //region wifi相关
    private void connectWifiDevice(DeviceBean deviceBean) {
        if (!SocketManager.getInstance().isWifiEnabled()) {
            ToastUtil.showToast(getActivity(), getString(R.string.please_open_wlan));
            return;
        }
        SocketManager.getInstance().connectDevice(deviceBean, new SocketManager.OnDeviceConnectListner() {
            @Override
            public void willConnectSocket() {
                //fixme 2025-5-26 Android 连接WIFI有自己的弹窗。
                // 然后， 连接socket很快，不需要loadingdialog
//                showLoadingDialog();
//                hideLoadingDialogDelay5000();
            }

            @Override
            public void onConnect(boolean suc, String msg) {
//                hideLoadingDialog();
                if (suc) {
                    toModeMenuActivity(ModeConstant.DeviceTypeS5);
                } else {
                    ToastUtil.showToast(getActivity(), msg);
                }
                Log.i("connectWifiDevice", "" + suc);
            }
        });
    }

    private void disconnectWifiDevice() {
        SocketManager.getInstance().disConnectSocket();
    }
    //endregion

    //region 蓝牙相关

    //连接到蓝牙
    private void connectBleDevice(int tId, String mac, String name, int deviceType) {
        if (TextUtils.isEmpty(mac)) {
            return;
        }
        showLoadingDialog();
        DFBleManager.getInstance().connectBt(tId, mac, name, deviceType);
    }

    private void disconnectBleDevice() {
        DFBleManager.getInstance().disConnect();
    }

    //获取发球机info
    private void connectBleMachine() {
        OnBleResponseHandler handler = new OnBleResponseHandler() {
            @Override
            public boolean onResponse(boolean success, int status, Object res) {
                ToastUtil.showToast(getActivity(), getString(R.string.success_ble));
                hideLoadingDialog();
                if (success) {
                    BleMachineInfoBean info = (BleMachineInfoBean) res;
                    //发球
                    if (info == null) {
                        toModeMenuActivity(ModeConstant.DeviceTypeS8);
                    } else {
                        toModeMenuActivity(info.getType());
                    }
                }
                return false;
            }
        };

        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            DFS8ProtocolManager.getInstance().connectMachine(handler);
        } else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            DFS6ProtocolManager.getInstance().connectMachine(handler);
        } else {
            //未知设备类型  都用S8的指令 （s8的指令会有特殊处理）
            DFS8ProtocolManager.getInstance().connectMachine(handler);
        }
    }
    //endregion


    //region    DFBleManager.OnBleManagerListner
    @Override
    public void onScanResult(List<DeviceBean> deviceBeanList) {

    }

    @Override
    public void onConnectBle(boolean success, DeviceBean deviceBean) {
        if (success) {
//            ToastUtil.showToast(getActivity(),"蓝牙连接成功！");

            hideLoadingDialogDelay5000();
            //获取发球机info
            connectBleMachine();
        } else {
            hideLoadingDialog();
            ToastUtil.showToast(getActivity(), getString(R.string.fail_ble));
        }
    }

    @Override
    public void onDisConnectBle() {
        hideLoadingDialog();
    }

    //endregion


    private void bindListItemClick(DeviceBean bindBean) {
//        if (BuildConfig.DEBUG) {
////            toModeMenuActivity(bindBean.getDeviceType());
//            toModeMenuActivity(ModeConstant.DeviceTypeS5);
//            return;
//        }
//        超5
        if (bindBean.getDeviceType() == ModeConstant.DeviceTypeS5
                || bindBean.getDeviceType() == ModeConstant.DeviceTypeS3) {
            //记录当前连接的是超3还是超5 方便自定义的时候保存
            AppCacheUtil.getInstance().setS3Ors5Type(bindBean.getDeviceType());

            if (this.onCheckPermissonsListner != null) {
                if (!this.onCheckPermissonsListner.onCheckWifiPermission()) {
                    //没有WIFI权限
                    return;
                }
            }

            //当前已连接到蓝牙 断开蓝牙
            if (DFBleManager.getInstance().isDidConnectBlueTooth()) {
                showDisconnectAlert(true, DFBleManager.getInstance().getBleDeviceBean());
                return;
            }
            //当前已连接到socket
            if (SocketManager.getInstance().didConnected()) {
                if (bindBean.isSameDevice(SocketManager.getInstance().getCurDeviceBean())) {
                    //连接的是自己 前往菜单页面
                    toModeMenuActivity(bindBean.getDeviceType());
                } else {
                    //	断开socket
                    showDisconnectAlert(false, SocketManager.getInstance().getCurDeviceBean());
                }
                return;
            }
            //当前既没有蓝牙,也没有socket 直接连接到WiFi设备
            showConnectAlert(false, bindBean);
            return;
        }

        if (this.onCheckPermissonsListner != null) {
            if (!this.onCheckPermissonsListner.onCheckBlePermission()) {
                //没有ble权限
                return;
            }
        }

        //超6 超8
        //当前已连接到socket
        if (SocketManager.getInstance().didConnected()) {
            //	断开socket
            showDisconnectAlert(true, SocketManager.getInstance().getCurDeviceBean());
            return;
        }

        //当前已连接到蓝牙 断开蓝牙
        if (DFBleManager.getInstance().isDidConnectBlueTooth()) {
            if (bindBean.isSameDevice(DFBleManager.getInstance().getBleDeviceBean())) {
                //是同一个设备  前往发球机菜单页面
                toModeMenuActivity(bindBean.getDeviceType());
            } else {
                //不是同一个设备  先断开
                showDisconnectAlert(true, DFBleManager.getInstance().getBleDeviceBean());
            }
        } else {
            //当前没有连接到任何蓝牙，连接蓝牙
            showConnectAlert(true, bindBean);
        }
    }

    private void showConnectAlert(boolean isBle, DeviceBean deviceBean) {
        String title = getString(R.string.connect_alert) + " '" + deviceBean.getAlias() + "'";
        String msg = "";
        CommonDialog dialog = new CommonDialog(getActivity(), title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    if (isBle) {
                        connectBleDevice(deviceBean.getTid() ,deviceBean.getMac(), deviceBean.getName(), deviceBean.getDeviceType());
                    } else {
                        connectWifiDevice(deviceBean);
                    }
                }
            }
        });
        dialog.setPositiveButton(getString(R.string.connect));
        dialog.show();
    }

    private void showDisconnectAlert(boolean isBle, DeviceBean deviceBean) {
        String title = getString(R.string.cur_connect_alert) + " '" + deviceBean.getAlias() + "'";
        String msg = getString(R.string.ble_connect_alert_2);
        CommonDialog dialog = new CommonDialog(getActivity(), title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    if (isBle) {
                        disconnectBleDevice();
                    } else {
                        disconnectWifiDevice();
                    }
                }
            }
        });
        dialog.setPositiveButton(getString(R.string.disconnect));
        dialog.show();
    }

    private void toModeMenuActivity(int type) {
        if (this.onToModeMenuListner != null) {
            this.onToModeMenuListner.toModeMenu(type);
        }

        DeviceBean deviceBean = null;
        if (type == ModeConstant.DeviceTypeS8 || type == ModeConstant.DeviceTypeS6) {
            deviceBean = DFBleManager.getInstance().getBleDeviceBean();
        } else if (type == ModeConstant.DeviceTypeS5 || type == ModeConstant.DeviceTypeS3) {
            deviceBean = SocketManager.getInstance().getCurDeviceBean();
        }
        if (deviceBean != null) {
            DataBaseApi.updateLastDevice(deviceBean, new DataBaseApi.OnDatabaseCommonListner() {
                @Override
                public void onCallback(boolean suc) {
                    if (suc) {
                        queryBindList();
                    }
                }
            });
        }
    }

    private void toDeviceInfoActivity(DeviceBean item) {
        Intent intent = DeviceInfoActivity.makeIntent(getActivity(), item);
        startActivity(intent);
    }

    private int dip2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private LoadingDialog loadingDialog = null;
    private void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(getActivity());
            loadingDialog.setMsg(getString(R.string.conecting___));
        }
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    private void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    //做一个延迟保证能取消
    private void hideLoadingDialogDelay5000() {
       new Handler().postDelayed(new Runnable() {
           @Override
           public void run() {
               hideLoadingDialog();
           }
       }, 5000);
    }


    public interface OnToModeMenuListner {
        void toModeMenu(int deviceType);
    }


    public interface OnCheckPermissonsListner {
        boolean onCheckBlePermission();
        boolean onCheckWifiPermission();
    }
}
